package com.lzk.jetpacktest.workmanager

import android.content.Context
import android.util.Log
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import com.lzk.jetpacktest.api.HttpRepository
import com.lzk.jetpacktest.coroutine.CoroutineViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import java.io.*
import java.lang.Exception
import java.lang.IllegalStateException

/**
 * @Author: LiaoZhongKai
 * @Date: 2021/8/31 11:22
 * @Description:
 */
class NetWorker(context: Context,params: WorkerParameters) : CoroutineWorker(context,params) {

    private val mHttpRepository = HttpRepository()
    private val MAX_RETRY_COUNT = 3

    override suspend fun doWork(): Result {
        var out: BufferedWriter? = null
        var result = Result.failure()
        try {
            val file = File(applicationContext.cacheDir.absolutePath+File.separator+ DIRECTORY_NAME+File.separator+ FILE_NAME)
            Log.d("TAG","parent path :${file.parentFile.absolutePath}")
            Log.d("TAG","file path :${file.absolutePath}")
            if (!file.parentFile.exists()){
                file.parentFile.mkdirs()
            }
            if (!file.exists()){
                file.createNewFile()
            }

            out = BufferedWriter(OutputStreamWriter(FileOutputStream(file,true)))
            for (i in 0 until 10){
                delay(1000)
                out.newLine()
                out.write("text:${i+1}")
                Log.d("TAG","write$i")
                if (i == 5){
                    throw IOException()
                }
            }
//            delay(5000)
//            val wxResponse = mHttpRepository.requestWxList()
//            val list = wxResponse.data
//            list.forEach {
//                out.write("author:${it.name}")
//                out.newLine()
//                Log.d("TAG","write${it.name}")
//            }
            result = Result.success()
        }catch (e: Exception){
            e.printStackTrace()
            //runAttemptCount：当前重试次数,默认值为0
            //进程杀掉后，重试次数不会重置
            if (runAttemptCount > MAX_RETRY_COUNT){
                result = Result.failure()
            }else{
                Log.d("TAG","retry_count:$runAttemptCount")
                result = Result.retry()
            }
        }finally {
            out?.flush()
            out?.close()
        }
        return result
    }
}